package com.jinlejia.erp.ui.home;

import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.bumptech.glide.Glide;
import com.jinlejia.erp.R;
import com.jinlejia.erp.base.ApiConfig;
import com.jinlejia.erp.base.MapCallBack;
import com.jinlejia.erp.bean.NoticeEnclosure;
import com.jinlejia.erp.bean.NoticeImage;
import com.jinlejia.erp.bean.NoticeMessage;
import com.jinlejia.erp.bean.NoticeTitle;
import com.jinlejia.erp.databinding.ActivityNoticeDetailBinding;
import com.jinlejia.erp.ui.common.CommonDialog;
import com.jinlejia.erp.ui.common.ImageViewPagerActivity;
import com.jinlejia.erp.ui.common.ProgressDialog;
import com.jinlejia.erp.utils.DataFilter;
import com.jinlejia.erp.utils.DateUtil;
import com.jinlejia.erp.utils.DownloadUtil;
import com.jinlejia.erp.utils.IntenetUtil;
import com.jinlejia.erp.utils.MimeType;
import com.jinlejia.erp.widget.ButtonCircleProgressBar;
import com.jinlejia.erp.widget.MyWebView;
import com.weight.CustomToast;
import com.zhy.http.okhttp.OkHttpUtils;

import net.idik.lib.slimadapter.SlimAdapter;
import net.idik.lib.slimadapter.SlimInjector;
import net.idik.lib.slimadapter.viewinjector.IViewInjector;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;

public class NoticeDetailActivity extends AppCompatActivity {

    private SlimAdapter slimAdapter;
    private ArrayList<String> imgList = new ArrayList<>();
//    private ArrayList<String> fileList = new ArrayList<>();
    private List<Object> data = new ArrayList<>();
    private ProgressDialog progressDialog;

    private ActivityNoticeDetailBinding binding;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this,R.layout.activity_notice_detail);
        binding.backBtn.setOnClickListener(v->finish());

        progressDialog = new ProgressDialog(this, "加载中...");
        progressDialog.show();
        binding.yfRecycler.setLayoutManager(new LinearLayoutManager(this));
        binding.yfRecycler.setHasFixedSize(true);
        slimAdapter = SlimAdapter.create()
                //标题信息
                .register(R.layout.layout_notice_header, new SlimInjector<NoticeTitle>() {
                    @Override
                    public void onInject(NoticeTitle data, IViewInjector injector) {
                        injector.text(R.id.title, data.getTitle())
                                .text(R.id.name, data.getName())
                                .text(R.id.time, data.getTime());
                    }
                })
                //文字信息
                .register(R.layout.layout_notice_text, new SlimInjector<NoticeMessage>() {
                    @Override
                    public void onInject(final NoticeMessage data, IViewInjector injector) {
//                        injector.text(R.id.text, data.getMsg());
                        injector.with(R.id.webview, new IViewInjector.Action<MyWebView>() {
                            @Override
                            public void action( MyWebView webview) {
                                webview.loadUrl(data.getMsg());
//                               textView.setText( Html.fromHtml(data.getMsg()) );
//                                textView.setMovementMethod(LinkMovementMethod.getInstance());

                            }
                        });
                    }
                })
                //图片列表
                .register(R.layout.layout_notice_image, new SlimInjector<NoticeImage>() {
                    @Override
                    public void onInject(final NoticeImage data, IViewInjector injector) {
                        injector.with(R.id.image, new IViewInjector.Action<ImageView>() {
                            @Override
                            public void action(ImageView view) {
                                Glide.with(NoticeDetailActivity.this).load(data.getUrl()).placeholder(R.mipmap.ic_no_img)
                                        .into(view);
                            }
                        })
                                .clicked(R.id.image, new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        Intent intent = new Intent(NoticeDetailActivity.this, ImageViewPagerActivity.class);
                                        intent.putStringArrayListExtra("imgs", imgList);
                                        intent.putExtra("check", "picture");
                                        intent.putExtra("position", imgList.indexOf(data.getUrl()) + 1);
                                        startActivity(intent);
                                    }
                                });
                    }
                })
                //附件(enclosure)
                .register(R.layout.layout_notice_enclosure, new SlimInjector<NoticeEnclosure>() {
                    @Override
                    public void onInject(final NoticeEnclosure data, IViewInjector injector) {
                        injector.text(R.id.name, data.getName())
                                .with(R.id.progressBar, new IViewInjector.Action<ButtonCircleProgressBar>() {
                                    @Override
                                    public void action(final ButtonCircleProgressBar mProgressBar) {

                                        if (!TextUtils.isEmpty(data.getNativePath())) {
                                            mProgressBar.setStatus(ButtonCircleProgressBar.Status.END);
                                            mProgressBar.setTag(data.getNativePath());
                                        } else {
                                            mProgressBar.setStatus(ButtonCircleProgressBar.Status.START);
                                            mProgressBar.setTag("");
                                        }
                                    }
                                })
                                .clicked(R.id.enclosure_layout, new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        final ButtonCircleProgressBar mProgressBar = (ButtonCircleProgressBar) v.findViewById(R.id.progressBar);
                                        if (mProgressBar.getStatus() == ButtonCircleProgressBar.Status.LOADING) {
                                            //下载中，停止下载
                                            mProgressBar.setStatus(ButtonCircleProgressBar.Status.START);
                                            DownloadUtil.get().cancelTag(data.getUrl());

                                        } else if (mProgressBar.getStatus() == ButtonCircleProgressBar.Status.START) {
                                            //初始状态，开始下载
                                            if (IntenetUtil.getNetworkState(NoticeDetailActivity.this) == IntenetUtil.NETWORN_WIFI) {
                                                //wifi环境直接下载
                                                downLoad(mProgressBar, data);
                                            } else {
                                                //移动网络提示是否继续下载
                                                CommonDialog dialog = new CommonDialog(NoticeDetailActivity.this, "提示", "当前为移动网络，是否继续?", "继续", "取消");
                                                dialog.show();
                                                dialog.setConfirmListener(new CommonDialog.OnConfirmListener() {
                                                    @Override
                                                    public void confirm() {
                                                        downLoad(mProgressBar, data);
                                                    }
                                                });
                                            }

                                        } else if (mProgressBar.getStatus() == ButtonCircleProgressBar.Status.END) {
                                            //已经下载，直接查看
                                            openFile(mProgressBar.getTag().toString());
                                        }
                                    }
                                });
                    }
                })
                .attachTo(binding.yfRecycler);



        OkHttpUtils.get().url(ApiConfig.NOTICE_DETAIL)
                .addParams("id", getIntent().getStringExtra("id"))
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                        if (null != progressDialog && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (DataFilter.filter(NoticeDetailActivity.this, response, null)) {
                            System.out.println(response.get("data"));
                            JSONObject jsonObject = JSON.parseObject(response.get("data").toString());
                            ArrayList<Map<String, Object>> attachList = new ArrayList<Map<String, Object>>();
                            if (jsonObject.containsKey("attachList"))
                                attachList = JSON.parseObject(jsonObject.getString("attachList"), new TypeReference<ArrayList<Map<String, Object>>>() {
                                });
                            ArrayList<NoticeImage> noticeImages = new ArrayList<>();
                            ArrayList<NoticeEnclosure> noticeEnclosures = new ArrayList<>();
                            for (int i = 0; i < attachList.size(); i++) {
                                Map<String, Object> map = attachList.get(i);
                                if (map.get("type").equals(1)) {
                                    //图片
                                    NoticeImage noticeImage = new NoticeImage(map.get("attachUrl").toString());
                                    noticeImages.add(noticeImage);
                                    imgList.add(noticeImage.getUrl());
                                } else {
                                    //附件
                                    String path = Environment.getExternalStorageDirectory().getAbsolutePath().concat(File.separator).concat("JljEnclosure").concat(File.separator)
                                            .concat(map.get("attachUrl").toString());
                                    if (new File(path).exists()) {
                                        //已下载
                                        noticeEnclosures.add(new NoticeEnclosure(map.get("attachName").toString(), map.get("attachUrl").toString(), path));
                                    } else {
                                        noticeEnclosures.add(new NoticeEnclosure(map.get("attachName").toString(), map.get("attachUrl").toString(), ""));
                                    }
                                }
                            }
                            //标题、发布人、时间
                            data.add(new NoticeTitle(jsonObject.getString("noticeTitle"), jsonObject.getString("issueName"), DateUtil.getTime(jsonObject.getLong("createTime"), "yyyy-M-d HH:mm:ss")));
                            //文字信息 jsonObject.getString("noticeContent").trim()
                            data.add(new NoticeMessage( ApiConfig.MAGEHEADER_URL().concat(jsonObject.getString("noticeContent"))));
                            data.addAll(noticeImages);
                            //附件
                            data.addAll(noticeEnclosures);
                            if (null != progressDialog && progressDialog.isShowing()) {
                                progressDialog.dismiss();
                            }
                            slimAdapter.updateData(data);

                        }
                    }
                });


    }

    private void downLoad(final ButtonCircleProgressBar mProgressBar, final NoticeEnclosure data) {
        mProgressBar.setStatus(ButtonCircleProgressBar.Status.LOADING);
        DownloadUtil.get().download(data.getUrl(), "JljEnclosure", data.getUrl(), new DownloadUtil.OnDownloadListener() {
            @Override
            public void onDownloadSuccess() {
                Observable
                        .empty()
                        .observeOn(AndroidSchedulers.mainThread())
                        .doOnCompleted(new Action0() {
                            @Override
                            public void call() {
                                mProgressBar.setStatus(ButtonCircleProgressBar.Status.END);
                                String path = Environment.getExternalStorageDirectory().getAbsolutePath().concat(File.separator).concat("JljEnclosure")
                                        .concat(data.getUrl().substring(data.getUrl().lastIndexOf("/")));
                                mProgressBar.setTag(path);
                            }
                        })
                        .subscribe();

            }

            @Override
            public void onDownloading(final int progress) {
                Observable
                        .empty()
                        .observeOn(AndroidSchedulers.mainThread())
                        .doOnCompleted(new Action0() {
                            @Override
                            public void call() {
                                mProgressBar.setStatus(ButtonCircleProgressBar.Status.LOADING);
                                mProgressBar.setProgress(progress);
                            }
                        })
                        .subscribe();

            }

            @Override
            public void onDownloadFailed() {
                Observable
                        .empty()
                        .observeOn(AndroidSchedulers.mainThread())
                        .doOnCompleted(new Action0() {
                            @Override
                            public void call() {
                                mProgressBar.setStatus(ButtonCircleProgressBar.Status.START);
                            }
                        })
                        .subscribe();
            }
        });
    }

    private void openFile(String path) {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(Intent.ACTION_VIEW);
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        File file = new File(path);
        //获取文件file的MIME类型
        String type = MimeType.getMIMEType(file);
        //设置intent的data和Type属性。
        intent.setDataAndType(Uri.fromFile(file), type);
        try {
            startActivity(intent);
        } catch (ActivityNotFoundException e) {
            CustomToast.showToast(NoticeDetailActivity.this, "您没有可以打开该文件的应用!", 1500);
        }
    }



    @Override
    protected void onDestroy() {
        if (null != progressDialog && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
        super.onDestroy();
    }
}
